from pydiscourse import DiscourseClient
from typing import List, Dict, Any, Optional
import logging

logger = logging.getLogger(__name__)

class DiscourseService:
    """Discourse API 服务类"""
    
    def __init__(self, base_url: str, api_key: str, username: str):
        """
        初始化 Discourse 客户端
        
        Args:
            base_url: Discourse 站点的基础 URL
            api_key: API 密钥
            username: 用户名
        """
        self.client = DiscourseClient(
            host=base_url,
            api_key=api_key,
            api_username=username
        )
    
    async def get_latest_posts(self, limit: int = 10) -> List[Dict[str, Any]]:
        """
        获取最新的帖子
        
        Args:
            limit: 限制返回的帖子数量
            
        Returns:
            List[Dict]: 帖子列表
        """
        try:
            posts = self.client.latest_posts(limit=limit)
            return posts
        except Exception as e:
            logger.error(f"Error fetching latest posts: {e}")
            return []
    
    async def search_posts_by_tags(self, tags: List[str], limit: int = 20) -> List[Dict[str, Any]]:
        """
        通过标签搜索帖子
        
        Args:
            tags: 标签列表
            limit: 限制返回的结果数量
            
        Returns:
            List[Dict]: 搜索结果，直接返回包含标签的帖子
        """
        try:
            if not tags:
                logger.warning("No tags provided for search")
                return []
            
            # 构建标签搜索查询
            tag_query = " ".join([f"#{tag}" for tag in tags])
            
            # 使用 Discourse 搜索 API
            results = self.client.search(tag_query, limit=limit)
            
            # 直接返回搜索到的帖子
            posts = results.get('posts', [])
            
            return posts[:limit]
            
        except Exception as e:
            logger.error(f"Error searching posts by tags {tags}: {e}")
            return []
    
    async def get_posts_with_any_tags(self, tags: List[str], limit: int = 20) -> List[Dict[str, Any]]:
        """
        获取包含任意指定标签的帖子（OR 查询）
        
        Args:
            tags: 标签列表
            limit: 限制返回的结果数量
            
        Returns:
            List[Dict]: 搜索结果，直接返回包含任意标签的帖子
        """
        try:
            if not tags:
                return []
            
            all_posts = []
            seen_post_ids = set()
            
            # 为每个标签单独搜索
            for tag in tags:
                try:
                    results = self.client.search(f"#{tag}", limit=limit)
                    posts = results.get('posts', [])
                    
                    for post in posts:
                        post_id = post.get('id')
                        if post_id and post_id not in seen_post_ids:
                            all_posts.append(post)
                            seen_post_ids.add(post_id)
                            
                except Exception as e:
                    logger.error(f"Error searching for tag '{tag}': {e}")
                    continue
            
            # 按创建时间排序并限制结果数量
            all_posts.sort(key=lambda x: x.get('created_at', ''), reverse=True)
            return all_posts[:limit]
            
        except Exception as e:
            logger.error(f"Error getting posts with any tags {tags}: {e}")
            return []
    
    async def get_posts_with_all_tags(self, tags: List[str], limit: int = 20) -> List[Dict[str, Any]]:
        """
        获取包含所有指定标签的帖子（AND 查询）
        
        Args:
            tags: 标签列表
            limit: 限制返回的结果数量
            
        Returns:
            List[Dict]: 搜索结果，直接返回包含所有标签的帖子
        """
        try:
            if not tags:
                return []
            
            # 构建包含所有标签的搜索查询
            tag_query = " ".join([f"#{tag}" for tag in tags])
            
            # 使用 Discourse 搜索 API
            results = self.client.search(tag_query, limit=limit)
            
            # 直接返回搜索到的帖子
            posts = results.get('posts', [])
            
            return posts[:limit]
            
        except Exception as e:
            logger.error(f"Error getting posts with all tags {tags}: {e}")
            return []

    async def search_posts(self, query: str, limit: int = 20) -> List[Dict[str, Any]]:
        """
        搜索帖子
        
        Args:
            query: 搜索关键词
            limit: 限制返回的结果数量
            
        Returns:
            List[Dict]: 搜索结果
        """
        try:
            results = self.client.search(query, limit=limit)
            return results.get('posts', [])
        except Exception as e:
            logger.error(f"Error searching posts: {e}")
            return []
    
    async def get_category_topics(self, category_id: int, limit: int = 20) -> List[Dict[str, Any]]:
        """
        获取特定分类下的主题
        
        Args:
            category_id: 分类 ID
            limit: 限制返回的主题数量
            
        Returns:
            List[Dict]: 主题列表
        """
        try:
            topics = self.client.category_topics(category_id, limit=limit)
            return topics.get('topic_list', {}).get('topics', [])
        except Exception as e:
            logger.error(f"Error fetching category topics: {e}")
            return []
    
    async def get_topic_posts(self, topic_id: int) -> List[Dict[str, Any]]:
        """
        获取特定主题下的所有帖子
        
        Args:
            topic_id: 主题 ID
            
        Returns:
            List[Dict]: 帖子列表
        """
        try:
            topic = self.client.topic_posts(topic_id)
            return topic.get('post_stream', {}).get('posts', [])
        except Exception as e:
            logger.error(f"Error fetching topic posts: {e}")
            return []
    
    async def create_post(self, title: str, content: str, category_id: Optional[int] = None) -> Dict[str, Any]:
        """
        创建新帖子
        
        Args:
            title: 帖子标题
            content: 帖子内容
            category_id: 分类 ID（可选）
            
        Returns:
            Dict: 创建结果
        """
        try:
            result = self.client.create_post(
                title=title,
                content=content,
                category_id=category_id
            )
            return result
        except Exception as e:
            logger.error(f"Error creating post: {e}")
            return {"error": str(e)}
